package com.ruoyi.project.zerocarbon.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.zerocarbon.domain.DeclarationGansu;
import com.ruoyi.project.zerocarbon.domain.DeclareJudge;
import com.ruoyi.project.zerocarbon.domain.DeclareRanking;
import com.ruoyi.project.zerocarbon.domain.export.gansu.DeclarationGansuExport;
import com.ruoyi.project.zerocarbon.domain.export.gansu.DeclarationGansuRankingExport;
import com.ruoyi.project.zerocarbon.mapper.DeclarationGansuMapper;
import com.ruoyi.project.zerocarbon.mapper.DeclareJudgeMapper;
import com.ruoyi.project.zerocarbon.mapper.DeclareRankingMapper;
import com.ruoyi.project.zerocarbon.service.IDeclarationGansuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @类名: ExportController
 * @描述:
 * @作者:
 * @日期: 2021/6/26 15:07
 */
@Slf4j
@Api(tags = "甘肃省导出")
@RequestMapping("/declarationgansu/export")
@RestController
public class DeclarationGansuExportController extends BaseController {
    @Autowired
    private DeclarationGansuMapper declarationGansuMapper;
    @Autowired
    private DeclareJudgeMapper declareJudgeMapper;
    @Autowired
    private IDeclarationGansuService declarationGansuService;
    @Autowired
    private DeclareRankingMapper declareRankingMapper;
    @Autowired
    private TokenService tokenService;

    private List<DeclarationGansu> selectOne(Long id){
        DeclarationGansu declaration = declarationGansuMapper.selectDeclarationDetailGansuById(id);
        List<DeclarationGansu> list = Arrays.asList(declaration);
        return list;
    }

    private DeclarationGansu selectRankingOne(Long id){
        DeclarationGansu declaration = declarationGansuMapper.selectDeclarationDetailGansuById(id);
        List<DeclareJudge> declareJudges = declareJudgeMapper.selectDeclareJudgeByDecorationId(declaration.getId());
        declaration.setDeclareJudges(declareJudges);
        if (!CollectionUtils.isEmpty(declareJudges)){
            Integer sum = declareJudges.stream().mapToInt(DeclareJudge::getScore).sum();
            declaration.setScore(Math.round(sum/4));
        }else {
            declaration.setScore(0);
        }
        DeclareRanking declareRanking = declareRankingMapper.selectDeclareRankingByDeclarationId(declaration.getId());
        Integer score = 0;
        if (declareRanking != null){
            score = declareRanking.getScore();
        }
        int ranking = declarationGansuMapper.getRankingNum(score) + 1;
        declaration.setRanking(ranking);

        return declaration;
    }

    private List<DeclarationGansu> selectList(List<Long> idList){
        List<DeclarationGansu> list = new ArrayList<>();
        for (Long id:idList){
            DeclarationGansu declaration = declarationGansuMapper.selectDeclarationDetailGansuById(id);
            if (declaration != null){
                list.add(declaration);
            }
        }
        return list;
    }

    /**
     * 项目报名列表
     * @param declarationGansu
     * @return
     */
    @ApiOperation("项目报名列表导出")
    @PostMapping("/signUp/list")
    public AjaxResult signUpList(@Validated @RequestBody DeclarationGansu declarationGansu) {
        List<DeclarationGansu> list = new ArrayList<>();
        if (declarationGansu.getId() != null){
            list = selectOne(declarationGansu.getId());
        }else if (CollectionUtils.isNotEmpty(declarationGansu.getIdList())){
            list = selectList(declarationGansu.getIdList());
        }else {
            startPage();
            declarationGansu.setSaveType(1);
            if (declarationGansu.getAuditStatus() == null) {
            } else if (declarationGansu.getAuditStatus() == 13) {
                declarationGansu.setAuditStatusList(Arrays.asList(13, 21, 22, 23, 24, 25));
            }
            list = declarationGansuService.selectDeclarationGansuListExport(declarationGansu);
        }
        List<DeclarationGansuExport> exportList = getExportList(list);

        ExcelUtil<DeclarationGansuExport> util = new ExcelUtil<DeclarationGansuExport>(DeclarationGansuExport.class);
        return util.exportExcel(exportList, "项目报名列表");
    }

    /**
     * 项目上报列表
     * @param declarationGansu
     * @return
     */
    @ApiOperation("项目上报列表导出")
    @PostMapping("/report/list")
    public AjaxResult reportList(@Validated @RequestBody DeclarationGansu declarationGansu) {
        List<DeclarationGansu> list = new ArrayList<>();
        if (declarationGansu.getId() != null){
            list = selectOne(declarationGansu.getId());
        }else if (CollectionUtils.isNotEmpty(declarationGansu.getIdList())){
            list = selectList(declarationGansu.getIdList());
        }else {
            startPage();
            if (declarationGansu.getAuditStatus() == null || declarationGansu.getAuditStatus() < 13) {
                declarationGansu.setAuditStatusList(Arrays.asList(13,21,22,24,25));
            }
            list = declarationGansuService.selectDeclarationGansuListExport(declarationGansu);
        }
        List<DeclarationGansuExport> exportList = getExportList(list);

        ExcelUtil<DeclarationGansuExport> util = new ExcelUtil<DeclarationGansuExport>(DeclarationGansuExport.class);
        return util.exportExcel(exportList, "项目上报列表");
    }

    /**
     * 项目审核列表导出
     * @param declarationGansu
     * @return
     */
    @ApiOperation("项目审核列表导出")
    @PostMapping("/check/list")
    public AjaxResult checkList(@Validated @RequestBody DeclarationGansu declarationGansu) {
        List<DeclarationGansu> list = new ArrayList<>();
        if (declarationGansu.getId() != null){
            list = selectOne(declarationGansu.getId());
        }else if (CollectionUtils.isNotEmpty(declarationGansu.getIdList())){
            list = selectList(declarationGansu.getIdList());
        }else {
            startPage();
            if (declarationGansu.getAuditStatus() == null || declarationGansu.getAuditStatus() < 21) {
                declarationGansu.setAuditStatusList(Arrays.asList(21, 24));
            }
            list = declarationGansuService.selectDeclarationGansuListExport(declarationGansu);
        }
        List<DeclarationGansuExport> exportList = getExportList(list);

        ExcelUtil<DeclarationGansuExport> util = new ExcelUtil<DeclarationGansuExport>(DeclarationGansuExport.class);
        return util.exportExcel(exportList, "项目审核列表");
    }

    /**
     * 项目分配列表
     * @param declarationGansu
     * @return
     */
    @ApiOperation("项目分配列表导出")
    @PostMapping("/distribution/list")
    public AjaxResult distributionList(@Validated @RequestBody DeclarationGansu declarationGansu) {
        List<DeclarationGansu> list = new ArrayList<>();
        if (declarationGansu.getId() != null){
            list = selectOne(declarationGansu.getId());
        }else if (CollectionUtils.isNotEmpty(declarationGansu.getIdList())){
            list = selectList(declarationGansu.getIdList());
        }else {
            startPage();
            if (declarationGansu.getAuditStatus() == null || declarationGansu.getAuditStatus() < 21) {
                declarationGansu.setAuditStatus(24);
            }
            list = declarationGansuService.selectDeclarationGansuList(declarationGansu);
        }
        List<DeclarationGansuExport> exportList = getExportList(list);

        ExcelUtil<DeclarationGansuExport> util = new ExcelUtil<DeclarationGansuExport>(DeclarationGansuExport.class);
        return util.exportExcel(exportList, "项目分配列表");
    }

    /**
     * 项目评分列表
     * @param declarationGansu
     * @return
     */
    @ApiOperation("项目评分列表导出")
    @PostMapping("/judge/list")
    public AjaxResult judgeList(@Validated @RequestBody DeclarationGansu declarationGansu) {
        List<DeclarationGansu> list = new ArrayList<>();
        ExcelUtil<DeclarationGansuExport> util = new ExcelUtil<DeclarationGansuExport>(DeclarationGansuExport.class);
        if (declarationGansu.getId() != null){
            DeclarationGansu declaration = selectRankingOne(declarationGansu.getId());
            list = Arrays.asList(declaration);
        }else if (CollectionUtils.isNotEmpty(declarationGansu.getIdList())){
            for (Long id:declarationGansu.getIdList()){
                list.add(selectRankingOne(id));
            }
        }else {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            String groupName = loginUser.getUser().getRemark();
            declarationGansu.setGroupName(groupName);
            if (StringUtils.isEmpty(groupName)){
                List<DeclarationGansuExport> exportList = new ArrayList<>();
                return util.exportExcel(exportList, "项目评分列表");
            }

            declarationGansu.setDistributionStatus(1);
            if (declarationGansu.getAuditStatus() == null || declarationGansu.getAuditStatus() < 23) {
                declarationGansu.setAuditStatus(24);
            }
            Integer pageNum = declarationGansu.getPageNum() != null ? declarationGansu.getPageNum() : 1;
            Integer pageSize = declarationGansu.getPageSize() != null ? declarationGansu.getPageSize() : 5000;
            String orderBy = "id desc";
            if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
                PageHelper.startPage(pageNum, pageSize);
            }
            List<DeclarationGansu> groupDecorationList;
            if (declarationGansu.getJudgeStatus() != null && declarationGansu.getJudgeStatus() ==0){
                declarationGansu.setUserName(loginUser.getUser().getUserName());
                groupDecorationList = declarationGansuMapper.getGroupDecorationListAndNoJudgeStatus(declarationGansu);
            }else if (declarationGansu.getJudgeStatus() != null && declarationGansu.getJudgeStatus() > 0){
                declarationGansu.setUserName(loginUser.getUser().getUserName());
                groupDecorationList = declarationGansuMapper.getGroupDecorationListAndJudgeStatus(declarationGansu);
            }else {
                groupDecorationList = declarationGansuMapper.getGroupDecorationList(declarationGansu);
            }
//            list = declarationGansuService.getJudgeDecorationListByVoList(groupDecorationList,declarationGansu.getJudgeStatus(),loginUser.getUser().getUserName());
            if (CollectionUtils.isNotEmpty(groupDecorationList)){
                List<Long> longList = groupDecorationList.stream().map(DeclarationGansu::getId).collect(Collectors.toList());
                DeclarationGansu model = new DeclarationGansu();
                model.setIdList(longList);
                list = declarationGansuService.selectDeclarationGansuList(model);
            }
        }
        List<DeclarationGansuExport> exportList = getExportList(list);

        return util.exportExcel(exportList, "项目评分列表");
    }

    private List<DeclarationGansuExport> getExportList(List<DeclarationGansu> list){
        List<DeclarationGansuExport> exportList = new ArrayList<>();
        for (DeclarationGansu declaration:list){
            DeclarationGansuExport exportModel = new DeclarationGansuExport();
            BeanUtils.copyProperties(declaration,exportModel);
            if (StringUtils.isNotEmpty(declaration.getAward1())){
                JSONObject jsonObj = JSONObject.parseObject(declaration.getAward1());
                if (jsonObj != null){
                    exportModel.setAward1Year(jsonObj.getString("yearAward"));
                    exportModel.setAward1Content(jsonObj.getString("awardInformation"));
                }
            }
            if (StringUtils.isNotEmpty(declaration.getAward2())){
                JSONObject jsonObj = JSONObject.parseObject(declaration.getAward2());
                if (jsonObj != null){
                    exportModel.setAward2Year(jsonObj.getString("yearAward"));
                    exportModel.setAward2Content(jsonObj.getString("awardInformation"));
                }
            }
            if (StringUtils.isNotEmpty(declaration.getAward3())){
                JSONObject jsonObj = JSONObject.parseObject(declaration.getAward3());
                if (jsonObj != null){
                    exportModel.setAward3Year(jsonObj.getString("yearAward"));
                    exportModel.setAward3Content(jsonObj.getString("awardInformation"));
                }
            }
            if (StringUtils.isNotEmpty(declaration.getCoreMemberInfor1())){
                JSONObject jsonObj = JSONObject.parseObject(declaration.getCoreMemberInfor1());
                if (jsonObj != null){
                    exportModel.setCoreMemberInfor1Name(jsonObj.getString("name"));
                    exportModel.setCoreMemberInfor1Politic(jsonObj.getString("politics"));
                    exportModel.setCoreMemberInfor1Work(jsonObj.getString("jobsharing"));
                }
            }
            if (StringUtils.isNotEmpty(declaration.getCoreMemberInfor2())){
                JSONObject jsonObj = JSONObject.parseObject(declaration.getCoreMemberInfor2());
                if (jsonObj != null){
                    exportModel.setCoreMemberInfor2Name(jsonObj.getString("name"));
                    exportModel.setCoreMemberInfor2Politic(jsonObj.getString("politics"));
                    exportModel.setCoreMemberInfor2Work(jsonObj.getString("jobsharing"));
                }
            }
            if (StringUtils.isNotEmpty(declaration.getCoreMemberInfor3())){
                JSONObject jsonObj = JSONObject.parseObject(declaration.getCoreMemberInfor3());
                if (jsonObj != null){
                    exportModel.setCoreMemberInfor3Name(jsonObj.getString("name"));
                    exportModel.setCoreMemberInfor3Politic(jsonObj.getString("politics"));
                    exportModel.setCoreMemberInfor3Work(jsonObj.getString("jobsharing"));
                }
            }
            if (StringUtils.isNotEmpty(declaration.getExternalCooperation1())){
                JSONObject jsonObj = JSONObject.parseObject(declaration.getExternalCooperation1());
                if (jsonObj != null){
                    exportModel.setExternalCooperation1Team(jsonObj.getString("organizationInfo"));
                    exportModel.setExternalCooperation1Support(jsonObj.getString("supportIssues"));
                }
            }
            if (StringUtils.isNotEmpty(declaration.getExternalCooperation2())){
                JSONObject jsonObj = JSONObject.parseObject(declaration.getExternalCooperation2());
                if (jsonObj != null){
                    exportModel.setExternalCooperation2Team(jsonObj.getString("organizationInfo"));
                    exportModel.setExternalCooperation2Support(jsonObj.getString("supportIssues"));
                }
            }
            if (StringUtils.isNotEmpty(declaration.getExternalCooperation3())){
                JSONObject jsonObj = JSONObject.parseObject(declaration.getExternalCooperation3());
                if (jsonObj != null){
                    exportModel.setExternalCooperation3Team(jsonObj.getString("organizationInfo"));
                    exportModel.setExternalCooperation3Support(jsonObj.getString("supportIssues"));
                }
            }
            exportList.add(exportModel);
        }
        return exportList;
    }

    /**
     * 项目排名列表
     * @param declarationGansu
     * @return
     */
    @ApiOperation("项目排名列表导出")
    @PostMapping("/ranking/list")
    public AjaxResult rankingList(@Validated @RequestBody DeclarationGansu declarationGansu) {
        List<DeclarationGansu> list = new ArrayList<>();
        if (declarationGansu.getId() != null){
            DeclarationGansu declaration = selectRankingOne(declarationGansu.getId());
            list = Arrays.asList(declaration);
        }else if (CollectionUtils.isNotEmpty(declarationGansu.getIdList())){
            for (Long id:declarationGansu.getIdList()){
                list.add(selectRankingOne(id));
            }
        }else {
            Integer pageNum = declarationGansu.getPageNum() != null ? declarationGansu.getPageNum() : 1;
            Integer pageSize = declarationGansu.getPageSize() != null ? declarationGansu.getPageSize() : 20000;
            String orderBy = "dr.score desc";
            if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
                PageHelper.startPage(pageNum, pageSize, orderBy);
            }

            if (declarationGansu.getAuditStatus() == null || declarationGansu.getAuditStatus() < 23) {
                declarationGansu.setAuditStatus(24);
            }
            declarationGansu.setDistributionStatus(1);
            list = declarationGansuService.getRankingDecorationList(declarationGansu);
        }
        ExcelUtil<DeclarationGansuRankingExport> util = new ExcelUtil<DeclarationGansuRankingExport>(DeclarationGansuRankingExport.class);
        List<DeclarationGansuRankingExport> exportList = new ArrayList<>();
        for (DeclarationGansu declaration:list){
            DeclarationGansuRankingExport exportModel = new DeclarationGansuRankingExport();
            BeanUtils.copyProperties(declaration,exportModel);
            if (CollectionUtils.isNotEmpty(declaration.getDeclareJudges())){
                if (declaration.getDeclareJudges().size() > 0){
                    exportModel.setExpert1(declaration.getDeclareJudges().get(0).getScore().doubleValue()/100);
                    exportModel.setRemark1(declaration.getDeclareJudges().get(0).getRemark());
                }
                if (declaration.getDeclareJudges().size() > 1){
                    exportModel.setExpert2(declaration.getDeclareJudges().get(1).getScore().doubleValue()/100);
                    exportModel.setRemark2(declaration.getDeclareJudges().get(1).getRemark());
                }
                if (declaration.getDeclareJudges().size() > 2){
                    exportModel.setExpert3(declaration.getDeclareJudges().get(2).getScore().doubleValue()/100);
                    exportModel.setRemark3(declaration.getDeclareJudges().get(2).getRemark());
                }
                if (declaration.getDeclareJudges().size() > 3){
                    exportModel.setExpert4(declaration.getDeclareJudges().get(3).getScore().doubleValue()/100);
                    exportModel.setRemark4(declaration.getDeclareJudges().get(3).getRemark());
                }
            }
            exportList.add(exportModel);
        }
        return util.exportExcel(exportList, "项目排名列表");
    }

}
